package com.xiaoshi.controller;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.xiaoshi.exception.PlatformException;
import com.xiaoshi.interfaces.Constants;
import com.xiaoshi.interfaces.MyHttpServiceMsg;
import com.xiaoshi.interfaces.ThreePushedDataReceiver;
import com.xiaoshi.utils.GsonUtils;
import com.xiaoshi.utils.JsonResult;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.util.ImageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class SecurityController<main> {

    @Autowired(required = false)
    private Map<String, ThreePushedDataReceiver> receivers = new HashMap<>();

    @Autowired
    private ConsumerTokenServices consumerTokenServices;




    @GetMapping("oauth/test")
    public String testOauth() {
        return "oauth";
    }

    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        return principal;
    }


    /**
     * 登出
     * @param request
     * @return
     * @throws PlatformException
     */
    @PostMapping("signout")
    public JsonResult signout(HttpServletRequest request) throws PlatformException {
        String authorization = request.getHeader(Constants.myConstans.AUTHORIZATION);
        String token = authorization.replace(Constants.myConstans.BEARER, StringUtils.EMPTY);
        if (!consumerTokenServices.revokeToken(token))
            throw new PlatformException(MyHttpServiceMsg.MSG_SINGIN_OUT_FAIL);

        return JsonResult.successMessage(MyHttpServiceMsg.MSG_SINGIN_OUT_SUCCESS);
    }


    /**
     * 手机验证码 60秒  不能重复点击
     * @return
     * @throws PlatformException
     */
//    @PostMapping("/phoneVerificationCode")
//    public JsonResult phoneVerificationCode(@RequestBody  PhoneVerificationCodeDto phoneVerificationCodeDto) throws PlatformException {
//        return  JsonResult.success(securityService.phoneVerificationCode(phoneVerificationCodeDto));
//
//    }


    /**
     * 注册
     * @param
     * @return
     * @throws
     */
    @PostMapping("register")
    public JsonResult register()  {

        return JsonResult.success("注册成功");
    }

    /**
     * @Description:  第三方推送
     * @author: sen
     * @Date: 2023/5/6 14:46
     * @param pustdata
     * @param request
     * @return: {@link JsonResult}
     */
    @PostMapping("/thirdNotify/{pustdata}")
    @ApiOperation("子系统推送数据")
    public  Object thirdDeviceDataReceive(@PathVariable String pustdata, HttpServletRequest request) {
        try {
            String msgData = "";
            if (request.getContentType().contains("application/json")) {
                msgData = getBodytxt(request);
            } else {
                Map<String, String[]> map = request.getParameterMap();
                msgData = GsonUtils.toJson(map);
            }

            if (StringUtils.isNotBlank(msgData)) {
                ThreePushedDataReceiver threePushedDataReceiver= receivers.get(pustdata);
                if(threePushedDataReceiver !=null){
                   return threePushedDataReceiver.threePushDataReceive(msgData);
                }
            }

            return JsonResult.success();
        } catch (Exception e) {
            return JsonResult.failMessage(e.getMessage());
        }
    }

    /**
     *  流变成数据  变成stream
     * @param request
     * @return
     */
    private String getBodytxt(HttpServletRequest request) {
        try (InputStream inStream = request.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream()) {
            int _buffer_size = 1024;
            byte[] tempBytes = new byte[_buffer_size];
            int count = -1;
            while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) {
                outStream.write(tempBytes, 0, count);
            }
            tempBytes = null;
            String result = new String(outStream.toByteArray(), "UTF-8");
            return result;
        } catch (IOException e) {
            log.error("Read data from request error", e);
        }
        return null;
    }



    @SneakyThrows
    public static void main(String[] args) {

        //设置APPID/AK/SK
         String APP_ID = "33195932";
        String API_KEY = "XOoyBp3vb5KF0192dvvacvYM";
        String SECRET_KEY = "mZ6yAThRGV5c9D6mrwHfUtq4exrESHsX";

//        String dateStr = "2024-01-30";
//        String str1 = getNmonthAfterV2(dateStr,12);
//        System.out.println(str1);


        // URL of the image to download
        String imageUrl = "https://dev-lyzk.andnext.cn/api/uaa-server/validata/code/0c443cac-017a-49c1-840d-1d6d51f794eb";

        // Create URL object and open input stream to the image
        URL url = new URL(imageUrl);
        InputStream inputStream = url.openStream();
        InputStream inputStream1 = url.openStream();

        FileOutputStream outputStream = new FileOutputStream("D://image.png");
        // Read bytes from the input stream and write to the output stream
        byte[] buffer = new byte[2048];
        int length;
        while ((length = inputStream1.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
//        //inputStream.close();
//        outputStream.close();
//        inputStream1.close();
//
//        // Close streams
//
//        // 初始化一个AipOcr
//        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
//
//        // 可选：设置网络连接参数
//        client.setConnectionTimeoutInMillis(2000);
//        client.setSocketTimeoutInMillis(60000);
//
//        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        //client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        //client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理
//
//        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
//        // 也可以直接通过jvm启动参数设置此环境变量
//        System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");
//        HashMap<String, String> options = new HashMap<String, String>();
//        options.put("language_type", "ENG");
//
//        // 调用接口
//        String path = "D://image.png";
//        JSONObject res = client.basicGeneral(path, options);
//        System.out.println(res.toString(2));





        try {
            // 创建实例
            ITesseract instance = new Tesseract();
            // 设置识别语言
            //设置训练库的位置
            instance.setDatapath("E:\\work\\tessdata");
            //  //chi_sim ：简体中文， eng    根据需求选择语言库
            instance.setLanguage("eng");
            //  instance.setTessVariable("tessedit_char_whitelist", "0123456789");
            // 设置识别引擎
            instance.setOcrEngineMode(0);
            // 读取文件
            BufferedImage image = ImageIO.read(inputStream);
            // 这里对图片黑白处理,增强识别率.这里先通过截图,截取图片中需要识别的部分
            image = ImageHelper.convertImageToGrayscale(image);
            // 图片锐化,自己使用中影响识别率的主要因素是针式打印机字迹不连贯,所以锐化反而降低识别率
            //image = ImageHelper.convertImageToBinary(image);
            // 图片放大5倍,增强识别率(很多图片本身无法识别,放大7倍时就可以轻易识,但是考滤到客户电脑配置低,针式打印机打印不连贯的问题,这里就放大7倍)
            image = ImageHelper.getScaledInstance(image, image.getWidth() * 7, image.getHeight() * 7);

            // 识别
            String result = instance.doOCR(image);
            System.out.println(result);



        } catch (Exception e) {
            System.err.println(e.getMessage());
        }finally {

            //inputStream.close();
            outputStream.close();
            inputStream1.close();
        }


    }


    public  static String getNmonthAfterV2(String dateStr,int month){
        Date date = DateUtil.parse(dateStr);

        DateTime endDate1 = DateUtil.endOfDay(date);

        Date endDate = DateUtil.offset(endDate1, DateField.MONTH, month);

        int monthStart = DateUtil.month(date);
        int monthEnd = DateUtil.month(endDate);
        System.out.println(monthStart  +"," + monthEnd);
        if(monthEnd > monthStart ){
            System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            if(monthStart == 1 && monthEnd == 2 ){
                if(DateUtil.isLeapYear(DateUtil.year(endDate))){
                    endDate = DateUtil.offset(endDate, DateField.DAY_OF_MONTH, 3);
                }else{
                    endDate = DateUtil.offset(endDate, DateField.DAY_OF_MONTH, 4);
                }
            }
        }else if(monthEnd <  monthStart ){
            System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<");
            if( monthEnd == 2 ){
                if(DateUtil.isLeapYear(DateUtil.year(endDate))){
                    endDate = DateUtil.offset(endDate, DateField.DAY_OF_MONTH, 3);
                }else{
                    endDate = DateUtil.offset(endDate, DateField.DAY_OF_MONTH, 4);
                }
            }
        }



        Date newDate1 = DateUtil.offset(endDate, DateField.DAY_OF_MONTH, -1);
        return  DateUtil.format(newDate1 ,"yyyy-MM-dd HH:mm:ss");
    }

}


